import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

///自定义图片预览页面
class MyPicturePreviewPage extends StatefulWidget {
  static const String routeName = '/my_picture_preview';

  final Map<String, dynamic> arguments;

  const MyPicturePreviewPage({super.key, required this.arguments});

  @override
  State<MyPicturePreviewPage> createState() => _MyPicturePreviewPageState();
}

class _MyPicturePreviewPageState extends State<MyPicturePreviewPage> with TickerProviderStateMixin {
  // Map<String, dynamic> imageData = {
  //   "imageUrls": [],
  //   "imageBase64s": [],
  //   "currentPage": 1,
  // };

  List<dynamic> imageUrls = [];
  List<dynamic> imageBase64s = [];
  List<MemoryImage> memoryImages = [];
  late int currentPage = 0;
  late String heroTag = "";
  @override
  void initState() {
    super.initState();
    imageUrls = widget.arguments['imageUrls'] ?? [];
    imageBase64s = widget.arguments['imageBase64s'] ?? [];
    currentPage = (int.parse(widget.arguments['currentPage'] ?? 0) + 1);

    if (imageBase64s.isNotEmpty) {
      for (var item in imageBase64s) {
        memoryImages.add(MemoryImage(base64Decode(item)));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double paddingBottom = MediaQuery.of(context).padding.bottom;
    heroTag = widget.arguments['heroTag'] ?? [];

    return GestureDetector(
      onTap: () {
        //点击屏幕关闭本页
        Navigator.pop(context);
      },
      child: Hero(
        tag: heroTag,
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Scaffold(
              backgroundColor: Colors.black,
              body: Center(
                //多图片预览
                child: PhotoViewGallery.builder(
                  itemCount: imageUrls.isNotEmpty ? imageUrls.length : imageBase64s.length,
                  pageController: PageController(initialPage: currentPage - 1),
                  onPageChanged: (index) {
                    setState(() {
                      currentPage = index + 1;
                    });
                  },
                  loadingBuilder: (context, event) => Center(
                    child: SizedBox(
                      width: 20.w,
                      height: 20.w,
                      child: const CircularProgressIndicator(
                        color: Colors.white,
                      ),
                    ),
                  ),
                  builder: (context, index) {
                    return imageUrls.isNotEmpty
                        ? PhotoViewGalleryPageOptions.customChild(
                            child: MyCachedNetworkImage(imageUrl: imageUrls[index]),
                            initialScale: PhotoViewComputedScale.contained,
                            minScale: PhotoViewComputedScale.contained * (0.5),
                            maxScale: PhotoViewComputedScale.covered * 1.1,
                          )
                        : PhotoViewGalleryPageOptions(
                            imageProvider: memoryImages[index],
                            initialScale: PhotoViewComputedScale.contained,
                            minScale: PhotoViewComputedScale.contained * (0.5),
                            maxScale: PhotoViewComputedScale.covered * 1.1,
                          );
                  },
                ),
              ),
            ),
            //图片张数指示器
            Positioned(
              left: 0,
              right: 0,
              bottom: 20,
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  imageUrls.isNotEmpty ? "$currentPage/${imageUrls.length}" : "$currentPage/${imageBase64s.length}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    decoration: TextDecoration.none,
                  ),
                ),
              ),
            ),
            //图片张数指示器
            Positioned(
              bottom: paddingBottom + 20,
              width: 120,
              height: 40,
              child: GestureDetector(
                onTap: () {
                  ///网络图片
                  // if (widget.urls != null && widget.urls.isNotEmpty) {
                  //   EcImageUtil.saveImage(widget.urls[_currentIndex]);
                  // }

                  // ///unit8List 图片
                  // if (widget.imageUnits != null && widget.imageUnits.isNotEmpty) {
                  //   EcImageUtil.saveImage('',
                  //       isAsset: true, imageUnit8List: widget.imageUnits[_currentIndex], toastSaveTip: '图片已保存到本地');
                  // }
                },
                child: MyBorder(
                  color: MyColours.textBlack.withOpacity(0.3),
                  backgroundColor: MyColours.textBlack.withOpacity(0.3),
                  radius: 20.h,
                  width: 0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      MyImage(imageName: "ic_save_image_icon", width: 20.w),
                      Container(
                        padding: EdgeInsets.only(left: 8.w),
                        child: Text(
                          "保存图片",
                          style: TextStyle(color: Colors.white, fontSize: 16.sp, decoration: null),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
